<template>
  <BasicLayout>
    <template #wrapper>
      <search-form label-width="34px" :col-span="4" :form-config="formConfig" :handler="handler" :form-data="formData" @onSubmit="onSubmit" />
      <section class="content" :style="{height: tableHeight+'px'}">
        <el-card class="card" shadow="hover">
          <div>
            <p class="title">门店总览</p>
            <ul>
              <li v-for="item in summaryData" :key="item.describe">
                <p class="number">
                  <i v-show="summaryLoad" class="el-icon-loading" />
                  <span v-show="!summaryLoad">{{ item.type===0&&item.number!==null?'￥':'' }}{{ item.number===null?'-':item.number }}</span>
                </p>
                <span class="desc">{{ item.describe }}</span>
              </li>
            </ul>
          </div>
        </el-card>
        <section class="chart-box">
          <el-card class="chart" shadow="hover">
            <div id="chart1" ref="chart1" :style="{ minWith: '300px', minHeight: '300px' }" />
          </el-card>
          <el-card class="chart" shadow="hover">
            <div id="chart2" ref="chart2" :style="{ minWith: '300px', minHeight: '300px' }" />
          </el-card>
        </section>
        <el-card shadow="hover">
          <div id="chart3" ref="chart3" :style="{ minWith: '300px', minHeight: '400px' }" />
        </el-card>
        <target-ranking-table ref="rankingTable" :params="formData" />
      </section>
    </template>
  </BasicLayout>
</template>

<script>
import SearchForm from '@/components/common/SearchForm';
import TargetRankingTable from './TargetRankingTable';
import config from './config';
import { getDictList } from '@/api/commonApi';
import { getStoreAchievementCityData } from '@/api/storeAchievementApi';
import { debounce, cloneDeep } from 'lodash';

const Echarts = require('echarts/lib/echarts');
// 引入折线图
require('echarts/lib/chart/line');
require('echarts/lib/chart/bar');
// 引入提示框和标题组件
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
require('echarts/lib/component/legend');
require('echarts/lib/component/legendScroll');

export default {
  name: 'KAliveStoreAchievementCity',
  components: {
    SearchForm,
    TargetRankingTable
  },
  data() {
    return {
      formConfig: config.formConfig,
      tableData: [],
      loading: false,
      count: 0,
      currentPage: 1,
      pageSize: 20,
      formData: {
        businessCategories: [],
        regions: [],
        cities: [],
        stores: [],
        dateType: 'YESTERDAY'
      },
      formCopy: {}, // 拷贝搜索栏查询数据
      handler: [
        { label: '查询', prop: 'submit', type: 'primary', eventName: 'onSubmit', icon: 'el-icon-search' },
        { label: '重置', prop: 'reset', type: 'default', eventName: 'onReset', icon: 'el-icon-refresh-right' }
      ],
      summaryData: [
        { type: 0, number: null, describe: '销售收入', props: 'salesIncome' },
        { type: 1, number: null, describe: '客单数', props: 'perCustomerCount' },
        { type: 0, number: null, describe: '客单价', props: 'perCustomerPrice' },
        { type: 0, number: null, describe: '件单价', props: 'perOnePrice' },
        { type: 0, number: null, describe: '前台毛利额', props: 'frontGrossProfit' },
        { type: 2, number: null, describe: '前台毛利率', props: 'frontGrossProfitRate' },
        { type: 0, number: null, describe: '销售毛利额', props: 'saleGrossProfit' },
        { type: 2, number: null, describe: '销售毛利率', props: 'salesGrossProfitRate' },
        { type: 1, number: null, describe: '有售SKU数量', props: 'onSaleSku' },
        { type: 2, number: null, describe: '有售SKU占比', props: 'onSaleSkuRate' },
        { type: 2, number: null, describe: '生鲜SKU数', props: 'freshSku' },
        { type: 2, number: null, describe: '生鲜SKU占比', props: 'freshSkuRate' },
        { type: 2, number: null, describe: '生鲜销售收入占比', props: 'freshRate' },
        { type: 2, number: null, describe: '库存金额', props: 'inventoryAmount' }
      ],
      summaryLoad: false,
      option: {
        title: { text: '' },
        legend: {
          data: []
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {}
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          nameLocation: 'center',
          nameTextStyle: {
            lineHeight: 24
          }
        },
        yAxis: [{ name: '单位', type: 'value', splitLine: { show: false }}],
        series: [],
        color: ['#35A2DA', '#34E31F']
      },
      chart1: null,
      chart2: null,
      load: {
        text: 'loading',
        color: '#5D80F7',
        textColor: '#5D80F7',
        maskColor: 'rgba(255, 255, 255, 0.8)'
      }
    };
  },
  inject: ['getTableHeight'],
  computed: {
    tableHeight() {
      return this.getTableHeight() + 40;
    }
  },
  watch: {
    // 业态类型级联接口查询
    'formData.businessCategories': {
      deep: true,
      handler(businessCategories) {
        this.onSearchCitiesByBusinessCategory({
          that: this,
          businessCategories
        });
      }
    },
    // 大区级联接口查询
    'formData.regions': {
      deep: true,
      handler(regions) {
        this.onSelectedRegions({ that: this, regions });
      }
    },
    // 城市级联接口查询
    'formData.cities': {
      deep: true,
      handler(cities) {
        this.onSelectedCities({ that: this, cities });
      }
    }
  },
  mounted() {
    this.initCharts();
    this.initOptions();
  },
  methods: {
    // 初始化图表显示
    initCharts() {
      for (let i = 1; i <= 3; i++) {
        this[`chart${i}`] = Echarts.init(document.getElementById(`chart${i}`));
        this[`chart${i}`].setOption(this.option);
      }
    },
    // 初始化所有选项
    initOptions() {
      const fetchBusiness = this.onFetchDict({
        type: 'BUSINESS_CATEGORY_DICT'
      }); // 获取商品分类
      const fetchRegions = this.onFetchDict({ type: 'REGION_DICT' }); // 获取大区
      const fetchCities = this.onFetchDict({ type: 'CITY_DICT' }); // 获取城市
      const fetchStores = this.onFetchDict({ type: 'STORE_DICT' }); // 获取店铺
      // 赋值操作
      Promise.all([
        fetchBusiness,
        fetchRegions,
        fetchCities,
        fetchStores
      ])
        .then(reslut => {
          [
            this.formConfig[0].options = [],
            this.formConfig[1].options = [],
            this.formConfig[2].options = [],
            this.formConfig[3].options = []
          ] = reslut || [];
        })
        .catch(error => console.log(error));
    },
    // 防抖查询业态下的门店
    onSearchCitiesByBusinessCategory: debounce(
      ({ that, businessCategories = [] }) => {
        const { cities, regions } = that.formData;
        that.formData.stores = undefined;
        that
          .onFetchDict({
            type: 'STORE_DICT',
            cities,
            regions,
            businessCategories
          })
          .then(storesOptions => {
            that.formConfig[3].options = storesOptions;
          });
      },
      800
    ),
    // 防抖查询城市下的
    onSelectedCities: debounce(({ that, cities = [] }) => {
      const { regions, businessCategories } = that.formData;
      that.formData.stores = undefined;
      that
        .onFetchDict({
          type: 'STORE_DICT',
          cities,
          regions,
          businessCategories
        })
        .then(storesOptions => {
          that.formConfig[3].options = storesOptions;
        });
    }, 800),
    // 防抖查询城市与商店选项
    onSelectedRegions: debounce(({ that, regions = [] }) => {
      that.formData.cities = undefined;
      that.formData.stores = undefined;
      const { businessCategories } = that.formData;
      const getCities = that.onFetchDict({ type: 'CITY_DICT', regions });
      const getStores = that.onFetchDict({
        type: 'STORE_DICT',
        regions,
        businessCategories
      });
      Promise.all([getCities, getStores]).then(
        ([citiesOptions = [], storesOptions = []]) => {
          that.formConfig[2].options = citiesOptions;
          that.formConfig[3].options = storesOptions;
        }
      );
    }, 800),
    // 字典接口
    onFetchDict({
      businessCategories = [],
      type = '',
      cities = [],
      regions = []
    } = {}) {
      return new Promise((resolve, reject) => {
        getDictList({
          businessCategories,
          type,
          cities,
          regions,
          reportType: 'REGION_CITY_SHOP'
        }).then(({ data, resultCode, resultMessage }) => {
          if (resultCode === '0000' && data) {
            resolve(data);
          } else {
            reject(resultMessage);
          }
        });
      });
    },
    // 点击查询
    onSubmit(form) {
      this.chart1.showLoading(this.load);
      this.chart2.showLoading(this.load);
      this.chart3.showLoading(this.load);
      this.summaryLoad = true;
      this.onGetData('getSalesIncomeList', form, (data) => {
        this.chart1.clear();
        this.chart1.setOption(this.handleChartsData(data, 'datetime', [{ name: '销售收入', type: 'line', string: 'salesIncomeFormatString', unit: 'unit' }], 'line'));
        this.chart1.hideLoading();
      });
      this.onGetData('getOrderReceiptCountList', form, (data) => {
        this.chart2.clear();
        this.chart2.setOption(this.handleChartsData(data, 'datetime', [{ name: '订单数', type: 'line', string: 'orderCountFormatString', unit: 'orderUnit' }, { name: '客单价', type: 'line', string: 'receiptFormatString', unit: 'receiptUnit', isDubbleY: true, yAxisIndex: 1 }], 'line'));
        this.chart2.hideLoading();
      });
      this.onGetData('getSalesIncomeCategoryList', form, (data) => {
        this.chart3.clear();
        const name1 = data.length ? data[0].lastDate : '';
        const name2 = data.length ? data[0].date : '';
        this.chart3.setOption(this.handleChartsData(data, 'category', [{ name: name2, type: 'bar', string: 'salesIncomeFormatString', unit: 'unit' }, { name: name1, type: 'bar', string: 'lastSalesIncomeFormatString', unit: 'unit' }], 'bar'));
        this.chart3.hideLoading();
      });
      this.onGetData('getSummaryData', form, (data) => {
        this.summaryData.forEach((item) => {
          if (item.props in data) {
            item.number = data[item.props];
          }
        });
        this.summaryLoad = false;
      });
      this.$refs.rankingTable.onFetchTableData();
    },
    handleChartsData(chart, xAxis, yAxis, type) {
      if (!chart.length) { return this.option; }
      const options = cloneDeep(this.option);
      const originYAxis = cloneDeep(yAxis);
      options.xAxis.data = chart.map(item => item[xAxis]);
      for (let i = 0; i < yAxis.length; i++) {
        const isOverZero = chart.some(item => Number(item[yAxis[i].string]) > 0);
        originYAxis[i].data = chart.map(item => item[yAxis[i].string]);
        if (isOverZero && type === 'bar') {
          yAxis[i].data = chart.map(item => {
            if (Number(item[yAxis[i].string]) === 0) {
              return null;
            }
            return item[yAxis[i].string];
          });
          yAxis[i].barMinHeight = 1;
        } else {
          yAxis[i].data = chart.map(item => item[yAxis[i].string]);
        }
        if (yAxis[i].isDubbleY) {
          options.yAxis.push({ name: `单位/${chart[0][yAxis[i].unit]}`, type: 'value', splitLine: { show: false }});
        } else {
          options.yAxis[0].name = `单位/${chart[0][yAxis[i].unit]}`;
        }
      }
      if (type === 'bar') {
        options.tooltip.axisPointer = { type: 'shadow' };
        options.tooltip.formatter = (res) => {
          let str = `${res[0].name}<br/>`;
          for (let i = 0; i < res.length; i++) {
            const item = res[i];
            const value = item.value == null ? originYAxis[item.seriesIndex].data[item.dataIndex] : item.value;
            str += `${item.marker} ${item.seriesName} ${value}<br/>`;
          }
          return str;
        };
      } else {
        options.xAxis.name = `单位/${chart[0].desc}`;
      }
      options.legend.data = yAxis.map(item => item.name);
      options.series = yAxis;
      return options;
    },
    onGetData(type, data, fun) {
      getStoreAchievementCityData(type, data).then(({ data, resultCode, resultMessage }) => {
        if (resultCode === '0000' && data) {
          if (Object.prototype.toString.call(fun) === '[object Function]') { fun(data); }
        } else {
          console.log(resultMessage);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.content{
  margin: 10px 0;
  padding: 0 10px 0 0;
  max-height: 750px;
  overflow-y: scroll;
  ::v-deep .el-card{
    margin: 10px 0;
    .el-card__body{
      padding: 10px 0;
    }
  }
  .card{
    padding: 0;
    ::v-deep .el-card__body{
      padding: 0;
    }
    .title{
      background-color: #e8eaec;
      padding: 10px;
    }
    ul{
      display: flex;
      overflow-x: scroll;
      width: 100%;
      li{
        padding: 20px 10px;
        text-align: center;
        flex-shrink: 0;
        flex-grow: 1;
        .number{
          font-size: 22px;
          color: #d80e0e;
        }
        .desc{
          font-size: 12px;
        }
      }
    }
  }
  .chart-box{
    display: flex;
    .chart{
      flex: 1;
      &:first-of-type{
        margin-right: 10px;
      }
    }
  }
}
.table{
  margin: 20px 0;
}
</style>
